<template>
  <div class="app-container">
    <!-- 页面标题和返回按钮 -->
    <div class="page-header">
      <h2 class="page-title">{{ pageTitle }}</h2>
    </div>

    <!-- 基本信息和时间范围选择 -->
    <el-card class="control-card" shadow="hover">
      <div slot="header" class="card-header">
        <span class="card-title">基本信息</span>
        <div class="header-controls">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange"
            style="margin-right: 10px;">
          </el-date-picker>
          <el-button type="primary" @click="refreshData">查询数据</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </div>
      </div>

      <el-row :gutter="20">
        <el-col :span="6">
          <div class="info-item">
            <label>应用：</label>
            <span>{{ basicInfo.appName }}</span>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="info-item">
            <label>渠道：</label>
            <span class="channel-tag"><dict-tag :options="dict.type.sys_channel" :value="basicInfo.channel"/></span>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="info-item">
            <label>维度：</label>
            <span>{{ getDimensionName(basicInfo.type) }}</span>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="info-item">
            <label>时间维度：</label>
            <span>{{ getTimeDimensionName(basicInfo.dataType) }}</span>
          </div>
        </el-col>
        <el-col :span="8" v-if="basicInfo.type === '3'">
          <div class="info-item">
            <label>账户：</label>
            <span>{{ basicInfo.accountName }} ( {{ basicInfo.accountId }} )</span>
          </div>
        </el-col>
        <el-col :span="8" v-if="basicInfo.type === '4'">
          <div class="info-item">
            <label>计划：</label>
            <span>{{ basicInfo.planName }} ( {{ basicInfo.planId }} )</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 图表区域 -->
    <el-card class="chart-card" shadow="hover" v-loading="chartLoading">
      <div slot="header" class="card-header">
        <span class="card-title">{{ getChartTitle() }}</span>
        <div class="chart-controls">
          <div class="metric-selection">
            <el-checkbox-group v-model="selectedMetrics" @change="updateChart">
              <el-checkbox label="cost">消耗</el-checkbox>
              <el-checkbox label="income">回收</el-checkbox>
              <el-checkbox label="roi">ROI</el-checkbox>
              <el-checkbox label="firstRoi">首日ROI</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <div id="trendChart" style="width: 100%; height: 400px;"></div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="table-card" shadow="hover">
      <div slot="header" class="card-header">
        <span class="card-title">数据列表</span>
      </div>

      <el-table
        v-loading="tableLoading"
        :data="tableData"
        :default-sort="defaultSort"
        style="width: 100%">

        <el-table-column label="日期" prop="acdate" min-width="1" align="center"/>

        <el-table-column label="小时" prop="hr" min-width="1" align="center" v-if="basicInfo.dataType === '1'">
          <template slot-scope="scope">
            {{ scope.row.hr || '00' }}:00
          </template>
        </el-table-column>

        <el-table-column label="消耗" prop="cost" min-width="1" align="center">
          <template slot-scope="scope">
            <div>账面: {{ scope.row.cost || 0 }}</div>
            <div style="color: #909399; font-size: 12px;">现金: {{ scope.row.cashCost || 0 }}</div>
          </template>
        </el-table-column>

        <el-table-column label="回收" prop="income" min-width="1" align="center">
          <template slot-scope="scope">
            <div>归因: {{ scope.row.income || 0 }}</div>
            <div style="color: #909399; font-size: 12px;">首日: {{ getFirstIncome(scope.row) }}</div>
          </template>
        </el-table-column>

        <el-table-column label="ROI" prop="roi" min-width="1" align="center">
          <template slot-scope="scope">
            <div>账面: {{ scope.row.roi || 0 }}</div>
            <div style="color: #909399; font-size: 12px;">首日: {{ getFirstIncomeRoi(scope.row) }}</div>
          </template>
        </el-table-column>

        <el-table-column label="利润" prop="profit" min-width="1" align="center">
          <template slot-scope="scope">
            {{ getProfit(scope.row) }}
          </template>
        </el-table-column>

        <!-- <el-table-column label="更新时间" prop="updatetime" min-width="1" align="center"/> -->
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { dataList } from "@/api/place-report/xiaomiSearch";
import { arrParamToStr, formatTime, computedDate } from '@/utils/index';
import echarts from 'echarts';

export default {
  name: 'MiSearchDataDetails',
  dicts: ['sys_channel'],
  data() {
    return {
      chartLoading: false,
      tableLoading: false,
      basicInfo: {},
      pageTitle: '数据详情',
      dateRange: [],
      selectedMetrics: ['cost','income','roi','firstRoi'], // 改为数组，默认选中消耗
      chart: null,
      chartData: [],
      tableData: [],
      total: 0,
      defaultSort: { prop: 'acdate', order: 'descending' },
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'acdate',
        isAsc: 'desc'
      },
      // 指标配置 - 优化颜色方案和视觉效果
      metricConfig: {
        cost: {
          name: '消耗',
          color: '#1E40AF', // 深蓝色，更高对比度
          lightColor: 'rgba(30, 64, 175, 0.1)', // 浅色用于面积图
          unit: '元',
          yAxisIndex: 0,
          type: 'amount',
          symbol: 'circle' // 数据点形状
        },
        income: {
          name: '回收',
          color: '#059669', // 深绿色，更鲜明
          lightColor: 'rgba(5, 150, 105, 0.1)',
          unit: '元',
          yAxisIndex: 0,
          type: 'amount',
          symbol: 'circle' // 方形数据点
        },
        roi: {
          name: 'ROI',
          color: '#DC2626', // 深红色，高对比度
          lightColor: 'rgba(220, 38, 38, 0.1)',
          unit: '',
          yAxisIndex: 1,
          type: 'ratio',
          symbol: 'circle' // 菱形数据点
        },
        firstRoi: {
          name: '首日ROI',
          color: '#7C3AED', // 紫色，独特识别
          lightColor: 'rgba(124, 58, 237, 0.1)',
          unit: '',
          yAxisIndex: 1,
          type: 'ratio',
          symbol: 'circle' // 三角形数据点
        }
      }
    }
  },
  created() {
    this.initBasicInfo();
    this.initDateRange();
    this.loadData();
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    // 初始化基本信息
    initBasicInfo() {
      this.basicInfo = {
        pkg: this.$route.query.pkg || '',
        appName: this.$route.query.appName || '',
        channel: this.$route.query.channel || '',
        type: this.$route.query.type || '',
        dataType: this.$route.query.dataType || '0', // 时间维度类型 (0:天, 1:小时)
        beginDate: this.$route.query.beginDate || '',
        endDate: this.$route.query.endDate || '',
        accountId: this.$route.query.accountId || '',
        accountName: this.$route.query.accountName || '',
        planId: this.$route.query.planId || '',
        planName: this.$route.query.planName || ''
      };
      // 设置页面标题
      this.pageTitle = `${this.getDimensionName(this.basicInfo.type)} - 数据详情`;
    },

    // 初始化日期范围
    initDateRange() {
      if (this.basicInfo.dataType === '1') {
        // 小时维度：使用从主页面传递过来的日期范围
        if (this.basicInfo.beginDate && this.basicInfo.endDate) {
          // 将8位数字格式转换为带连字符的格式
          const startDate = this.formatDateString(this.basicInfo.beginDate);
          const endDate = this.formatDateString(this.basicInfo.endDate);
          this.dateRange = [startDate, endDate];
        } else {
          // 如果没有传入日期参数，小时维度默认显示7天数据
          const endDate = computedDate(new Date());
          const startDate = computedDate(new Date());;
          this.dateRange = [startDate, endDate];
        }
      } else {
        // 天维度：始终查询最近30天的数据，忽略传入的日期参数
        const endDate = this.formatDateString(computedDate(new Date()));
        const startDate = this.formatDateString(this.getDateBefore(endDate, 30));
        this.dateRange = [startDate, endDate];
      }
    },

    // 获取指定日期前N天的日期
    getDateBefore(dateStr, days) {
      const date = new Date(dateStr.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'));
      date.setDate(date.getDate() - days);
      return date.toISOString().slice(0, 10).replace(/-/g, '');
    },

    // 格式化日期字符串：将8位数字格式转换为带连字符的格式
    formatDateString(dateStr) {
      if (!dateStr) return '';
      // 如果已经是带连字符的格式，直接返回
      if (dateStr.includes('-')) return dateStr;
      // 将8位数字格式（如 "20231201"）转换为带连字符的格式（如 "2023-12-01"）
      if (dateStr.length === 8) {
        return `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}`;
      }
      return dateStr;
    },

    // 获取维度名称
    getDimensionName(type) {
      const dimensionMap = {
        '3': '账户',
        '4': '计划',
        '6': '创意'
      };
      return dimensionMap[type] || '未知';
    },

    // 获取时间维度名称
    getTimeDimensionName(dataType) {
      const timeDimensionMap = {
        '0': '天',
        '1': '小时'
      };
      return timeDimensionMap[dataType] || '天';
    },

    // 日期范围变化处理
    handleDateRangeChange() {
      this.loadData();
    },

    // 刷新数据
    refreshData() {
      this.loadData();
    },

    resetQuery(){
      this.initDateRange();
      this.loadData();
    },

    // 加载数据
    loadData() {
      this.chartLoading = true;
      this.tableLoading = true;
      const queryParams = this.buildQueryParams();
      queryParams.dataType = this.basicInfo.dataType;
      queryParams.orderByColumn = 'acdate';
      queryParams.isAsc = 'descending';

      dataList(arrParamToStr(queryParams)).then(response => {
        this.chartData = response.rows.map(item => ({
          ...item,
          arpuData: item.arpuData ? JSON.parse(item.arpuData) : null,
          convertData: item.convertData ? JSON.parse(item.convertData) : null,
          behaviorData: item.behaviorData ? JSON.parse(item.behaviorData) : null
        }));
        this.updateChart();
        this.chartLoading = false;

        this.tableData = response.rows.map(item => ({
          ...item,
          updatetime: formatTime(item.updatetime),
          arpuData: item.arpuData ? JSON.parse(item.arpuData) : null
        }));
        this.total = response.total;
        this.tableLoading = false;
      }).catch(error => {
        console.error('加载图表数据失败:', error);
        this.$modal.msgError('加载图表数据失败');
        this.chartLoading = false;
        this.tableLoading = false;
      });
    },

    // 构建查询参数
    buildQueryParams() {
      const queryParams = {
        type: this.basicInfo.type,
        pkg: this.basicInfo.pkg,
        channel: this.basicInfo.channel,
        pageNum: 1,
        pageSize: 100,
        beginDate: this.dateRange[0].replace(/-/g, ''),
        endDate: this.dateRange[1].replace(/-/g, '')
      };

      // 根据维度添加对应的ID参数
      if (this.basicInfo.type === '3') {
        queryParams.accountId = [this.basicInfo.accountId];
      } else if (this.basicInfo.type === '4') {
        queryParams.accountId = [this.basicInfo.accountId];
        queryParams.planId = [this.basicInfo.planId];
      }

      return queryParams;
    },

    // 初始化图表
    initChart() {
      this.$nextTick(() => {
        const chartDom = document.getElementById('trendChart');
        if (chartDom) {
          this.chart = echarts.init(chartDom);
          window.addEventListener('resize', () => {
            if (this.chart) {
              this.chart.resize();
            }
          });
        }
      });
    },

    // 更新图表 - 支持双Y轴多指标显示
    updateChart() {
      if (!this.chart || !this.chartData.length) return;

      // 如果没有选中任何指标，完全清空图表
      if (!this.selectedMetrics || this.selectedMetrics.length === 0) {
        const emptyOption = {
          title: {
            text: '请选择要显示的指标',
            left: 'center',
            textStyle: {
              color: '#999',
              fontSize: 16
            }
          },
          tooltip: {},
          legend: { show: false },
          xAxis: {
            show: false,
            type: 'category',
            data: []
          },
          yAxis: [
            { show: false, type: 'value' },
            { show: false, type: 'value' }
          ],
          series: []
        };
        this.chart.setOption(emptyOption, true); // 使用notMerge=true完全替换配置
        return;
      }

      // 根据时间维度生成不同的时间标签
      const dates = this.basicInfo.dataType === '1'
        ? [...new Set(this.chartData.map(item => `${item.acdate}-${String(item.hr || 0).padStart(2, '0')}`))]
            .sort((a, b) => {
              const [dateA, hourA] = a.split('-');
              const [dateB, hourB] = b.split('-');
              if (dateA !== dateB) return parseInt(dateA) - parseInt(dateB);
              return parseInt(hourA) - parseInt(hourB);
            })
        : [...new Set(this.chartData.map(item => String(item.acdate)))].sort((a, b) => parseInt(a) - parseInt(b));

      // 检查是否需要双Y轴
      const hasAmountMetrics = this.selectedMetrics.some(m => this.metricConfig[m].type === 'amount');
      const hasRatioMetrics = this.selectedMetrics.some(m => this.metricConfig[m].type === 'ratio');
      const needDualAxis = hasAmountMetrics && hasRatioMetrics;

      // 为每个选中的指标创建数据系列
      const series = this.selectedMetrics.map(metric => {
        const values = dates.map(dateLabel => {
          let item;
          if (this.basicInfo.dataType === '1') {
            // 小时维度：dateLabel格式为 "20231201-14"
            const [acdate, hr] = dateLabel.split('-');
            const targetAcdate = parseInt(acdate);
            const targetHr = parseInt(hr);
            item = this.chartData.find(d => d.acdate === targetAcdate && (d.hr || 0) === targetHr);
          } else {
            // 天维度：dateLabel格式为 "20231201"
            const targetAcdate = parseInt(dateLabel);
            item = this.chartData.find(d => d.acdate === targetAcdate);
          }

          if (!item) {
            return 0;
          }

          let value;
          // 如果是首日ROI，需要计算
          if (metric === 'firstRoi') {
            const firstIncome = this.getFirstIncome(item);
            const cost = parseFloat(item.cost) || 0;
            value = cost > 0 ? parseFloat((firstIncome / cost).toFixed(2)) : 0;
          } else {
            // 确保数值转换正确
            const rawValue = item[metric];
            if (typeof rawValue === 'number') {
              value = rawValue;
            } else if (typeof rawValue === 'string') {
              value = parseFloat(rawValue) || 0;
            } else {
              value = 0;
            }
          }
          return value;
        });
        const config = this.metricConfig[metric];
        // 确保数据是数字类型
        const numericValues = values.map(v => {
          const num = Number(v);
          return isNaN(num) ? 0 : num;
        });
        return {
          name: config.name,
          type: 'line',
          yAxisIndex: needDualAxis ? config.yAxisIndex : 0,
          data: numericValues,
          smooth: true,
          // 增强线条样式
          lineStyle: {
            color: config.color,
            width: 5, // 增加线条粗细到5px
            shadowColor: config.color,
            shadowBlur: 3,
            shadowOffsetY: 2
          },
          // 增强数据点样式
          itemStyle: {
            color: config.color,
            borderColor: '#fff',
            borderWidth: 2,
            shadowColor: config.color,
            shadowBlur: 5
          },
          // 显示数据点标记
          symbol: config.symbol,
          symbolSize: this.isMobile() ? 6 : 8, // 移动端稍小的数据点
          showSymbol: true, // 始终显示数据点
          // 鼠标悬停时放大数据点
          emphasis: {
            itemStyle: {
              borderWidth: 3,
              shadowBlur: 8
            },
            lineStyle: {
              width: 6,
              shadowBlur: 5
            }
          },
          // 只有一个指标时显示面积图
          areaStyle: this.selectedMetrics.length === 1 ? {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: config.lightColor.replace('0.1', '0.3')
              }, {
                offset: 1, color: config.lightColor
              }]
            }
          } : null
        };
      });

      // 构建Y轴配置 - 增强视觉效果
      const yAxisConfig = needDualAxis ? [
        {
          type: 'value',
          name: '金额(元)',
          position: 'left',
          min: function(value) {
            return Math.max(0, value.min - (value.max - value.min) * 0.1);
          },
          max: function(value) {
            return value.max + (value.max - value.min) * 0.1;
          },
          nameTextStyle: {
            color: '#374151',
            fontSize: 13,
            fontWeight: '500'
          },
          axisLabel: {
            formatter: '{value}',
            color: '#6b7280',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#d1d5db'
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#f3f4f6',
              type: 'dashed'
            }
          }
        },
        {
          type: 'value',
          name: 'ROI',
          position: 'right',
          min: function(value) {
            return Math.max(0, value.min - (value.max - value.min) * 0.1);
          },
          max: function(value) {
            return value.max + (value.max - value.min) * 0.1;
          },
          nameTextStyle: {
            color: '#374151',
            fontSize: 13,
            fontWeight: '500'
          },
          axisLabel: {
            formatter: '{value}',
            color: '#6b7280',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#d1d5db'
            }
          },
          splitLine: {
            show: false
          }
        }
      ] : [
        {
          type: 'value',
          name: this.getYAxisName(),
          min: function(value) {
            return Math.max(0, value.min - (value.max - value.min) * 0.1);
          },
          max: function(value) {
            return value.max + (value.max - value.min) * 0.1;
          },
          nameTextStyle: {
            color: '#374151',
            fontSize: 13,
            fontWeight: '500'
          },
          axisLabel: {
            formatter: '{value}',
            color: '#6b7280',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#d1d5db'
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#f3f4f6',
              type: 'dashed'
            }
          }
        }
      ];

      const option = {
        title: {
          text: this.getChartTitle(),
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#1f2937'
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e5e7eb',
          borderWidth: 1,
          textStyle: {
            color: '#374151',
            fontSize: 14
          },
          formatter: (params) => {
            let result = `<div style="font-weight: bold; margin-bottom: 8px; color: #1f2937;">${params[0].axisValue}</div>`;
            params.forEach(param => {
              const metric = this.selectedMetrics.find(m => this.metricConfig[m].name === param.seriesName);
              const config = this.metricConfig[metric];
              result += `<div style="margin: 4px 0;">
                <span style="display: inline-block; width: 12px; height: 12px; background: ${config.color}; border-radius: 50%; margin-right: 8px;"></span>
                <span style="font-weight: 500;">${param.seriesName}:</span>
                <span style="color: ${config.color}; font-weight: bold;">${param.value}${config.unit}</span>
              </div>`;
            });
            return result;
          }
        },
        legend: {
          show: this.selectedMetrics.length > 1,
          top: 35,
          itemGap: this.isMobile() ? 15 : 20, // 移动端减少间距
          itemWidth: this.isMobile() ? 16 : 18, // 移动端稍小的图例标记
          itemHeight: this.isMobile() ? 12 : 14,
          textStyle: {
            fontSize: this.isMobile() ? 12 : 14,
            fontWeight: '500',
            color: '#374151'
          },
          backgroundColor: 'rgba(249, 250, 251, 0.8)',
          borderColor: '#e5e7eb',
          borderWidth: 1,
          borderRadius: 6,
          padding: this.isMobile() ? [6, 12] : [8, 16],
          data: this.selectedMetrics.map(metric => ({
            name: this.metricConfig[metric].name,
            icon: this.getLegendIcon(metric)
          }))
        },
        grid: {
          top: this.selectedMetrics.length > 1 ? (this.isMobile() ? 90 : 80) : (this.isMobile() ? 60 : 50),
          left: needDualAxis ? (this.isMobile() ? 50 : 60) : (this.isMobile() ? 40 : 50),
          right: needDualAxis ? (this.isMobile() ? 50 : 60) : (this.isMobile() ? 20 : 30),
          bottom: this.basicInfo.dataType === '1' ? (this.isMobile() ? 80 : 70) : (this.isMobile() ? 40 : 50) // 小时维度需要更多底部空间
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            formatter: (value) => {
              if (this.basicInfo.dataType === '1') {
                // 小时维度：value格式为 "20231201-14"
                const [dateStr, hour] = value.split('-');
                return `${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}\n${hour}:00`;
              } else {
                // 天维度：value格式为 "20231201"
                return value.slice(4, 6) + '-' + value.slice(6, 8);
              }
            },
            color: '#6b7280',
            fontSize: this.isMobile() ? 10 : 12,
            rotate: 0, // 不旋转，使用换行显示
            interval: this.basicInfo.dataType === '1' ? 'auto' : 0, // 小时维度自动间隔显示
            margin: this.basicInfo.dataType === '1' ? 15 : 8 // 增加标签间距
          },
          axisLine: {
            lineStyle: {
              color: '#d1d5db'
            }
          }
        },
        yAxis: yAxisConfig,
        series: series
      };
      this.chart.setOption(option, true); // 使用notMerge=true确保完全替换
    },

    // 获取首日回收
    getFirstIncome(row) {
      if (row.arpuData && row.arpuData.firstIncome !== undefined) {
        return row.arpuData.firstIncome;
      }
      return row.firstIncome || 0;
    },

    // 获取首日回收ROI
    getFirstIncomeRoi(row) {
      const firstIncome = this.getFirstIncome(row);
      const cost = row.cost || 0;
      return cost > 0 ? (firstIncome / cost).toFixed(2) : '0.00';
    },

    // 获取图表标题
    getChartTitle() {
      if (!this.selectedMetrics || this.selectedMetrics.length === 0) {
        return '数据趋势图';
      }

      if (this.selectedMetrics.length === 1) {
        return `${this.metricConfig[this.selectedMetrics[0]].name}趋势`;
      }

      const names = this.selectedMetrics.map(metric => this.metricConfig[metric].name);
      return `${names.join('、')}对比趋势`;
    },

    // 获取Y轴名称（单轴模式）
    getYAxisName() {
      if (!this.selectedMetrics || this.selectedMetrics.length === 0) {
        return '';
      }

      const hasAmountMetrics = this.selectedMetrics.some(m => this.metricConfig[m].type === 'amount');
      const hasRatioMetrics = this.selectedMetrics.some(m => this.metricConfig[m].type === 'ratio');

      if (hasAmountMetrics && !hasRatioMetrics) {
        return '金额(元)';
      } else if (!hasAmountMetrics && hasRatioMetrics) {
        return 'ROI';
      } else {
        return '数值';
      }
    },

    // 获取图例图标
    getLegendIcon(metric) {
      const symbolMap = {
        'circle': 'circle',
        'rect': 'rect',
        'diamond': 'diamond',
        'triangle': 'triangle'
      };
      return symbolMap[this.metricConfig[metric].symbol] || 'circle';
    },

    // 检测是否为移动端
    isMobile() {
      return window.innerWidth <= 768;
    },

    // 获取利润
    getProfit(row) {
      const income = row.income || 0;
      const cashCost = row.cashCost || 0;
      return (income - cashCost).toFixed(2);
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    margin: 0 0 0 15px;
    font-size: 24px;
    font-weight: bold;
    color: #303133;
  }
}

.control-card, .chart-card, .table-card {
  margin-bottom: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;

    .card-title {
      font-size: 18px;
      font-weight: bold;
      color: #303133;
      flex-shrink: 0;
    }

    .header-controls, .chart-controls {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
}

.info-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-wrap: nowrap;

  label {
    font-weight: bold;
    color: #606266;
    margin-right: 8px;
    white-space: nowrap;
    flex-shrink: 0;
  }

  span {
    color: #303133;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    flex: 1;

    // 针对dict-tag组件的特殊样式
    .el-tag {
      white-space: nowrap;
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  // 渠道标签特殊样式
  .channel-tag {
    display: inline-block;
    white-space: nowrap;

    .el-tag {
      white-space: nowrap;
      display: inline-block;
      max-width: 100px;
      overflow: hidden;
      text-overflow: ellipsis;
      vertical-align: middle;
    }
  }
}

.chart-card {
  .chart-controls {
    .metric-selection {
      .el-checkbox-group {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;

        .el-checkbox {
          margin-right: 0;

          .el-checkbox__label {
            padding-left: 8px;
            font-size: 14px;
          }
        }
      }
    }
  }
}

#trendChart {
  min-height: 400px;
}

.table-card {
  .el-table {
    .el-table__header {
      th {
        background-color: #f8f9fa;
        color: #606266;
        font-weight: bold;
      }
    }

    .el-table__body {
      tr:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;

    .page-title {
      margin: 10px 0 0 0;
    }
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;

    .header-controls, .chart-controls {
      margin-top: 10px;
      width: 100%;
    }
  }

  .info-item {
    margin-bottom: 15px;
    flex-direction: column;
    align-items: flex-start;

    label, span {
      display: block;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 100%;
    }

    span {
      margin-top: 5px;
      padding-left: 10px;
    }

    .channel-tag {
      width: 100%;

      .el-tag {
        max-width: calc(100% - 10px);
      }
    }
  }

  #trendChart {
    height: 300px;
  }

  // 移动端图表优化
  .chart-card {
    .card-header {
      .card-title {
        font-size: 16px;
      }
    }
  }
}

@media (max-width: 480px) {
  .app-container {
    padding: 10px;
  }

  .chart-controls {
    .metric-selection {
      .el-checkbox-group {
        flex-direction: column;
        gap: 8px;

        .el-checkbox {
          .el-checkbox__label {
            font-size: 12px;
          }
        }
      }
    }
  }
}
</style>
